package cn.hdax.test1;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;


public class WordCount {


    public static class WordCountMapper extends Mapper<LongWritable,Text,Text,LongWritable>
    {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            System.out.println(key.get() + " -- " + value.toString());

            String[] words = value.toString().split(" ") ;
            for(String s : words){
                context.write(new Text(s),new LongWritable(1));
            }

        }
    }

    public static class WordCountReduce extends Reducer<Text,LongWritable,Text,LongWritable>
    {
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long sum = 0 ;
           for(LongWritable v :values){
                sum = sum + v.get() ;
            }

            context.write(key,new LongWritable(sum));
        }
    }

    //定制作业 Job
    public static void main(String[] args) throws Exception{
        //
        Configuration configuration = new Configuration() ;
        //
        Job job = Job.getInstance(configuration,"wordcount") ;
        job.setJarByClass(WordCount.class);
        //
        Path pathin = new Path("/a1.txt") ;
        job.setMapperClass(WordCountMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);
        FileInputFormat.setInputPaths(job,pathin);


        //
        Path pathout = new Path("/t176/out") ;

        FileSystem fileSystem = FileSystem.get(configuration) ;
        if(fileSystem.exists(pathout)){
            fileSystem.delete(pathout,true) ;
        }

        job.setReducerClass(WordCountReduce.class);
        job.setOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);
        FileOutputFormat.setOutputPath(job,pathout);

        //提交作业
      //  boolean flag = job.waitForCompletion(true) ;
       /* if(flag){
            System.exit(0);
        }
        else{
            System.exit(1);
        }*/

       System.exit(job.waitForCompletion(true) ?0 : 1);

    }

}
